package com.maxd.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.maxd.error.DescribeException;
import com.maxd.error.ExceptionEnum;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JsonUtils {

    private static final ObjectMapper objectMapper = new ObjectMapper();
    static {
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }


    public static String toJsonString(Object data) {
        try {
            return objectMapper.writeValueAsString(data);
        } catch (Exception e) {
            log.error("jackson序列化异常.", e);
            throw new DescribeException(ExceptionEnum.SERIALIZE_ERROR);
        }
    }

    public static <T> T parseObject(String content, TypeReference<T> typeReference) {
        try {
            return objectMapper.readValue(content, typeReference);
        } catch (Exception e) {
            log.error("jackson反列化异常.", e);
            throw new DescribeException(ExceptionEnum.DESERIALIZE_ERROR);
        }
    }

    public static JsonNode readNode(byte[] bytes) {
        try {
            return objectMapper.readTree(bytes);
        } catch (Exception e) {
            log.error("jackson反列化异常.", e);
            throw new DescribeException(ExceptionEnum.DESERIALIZE_ERROR);
        }
    }

}
